#include "02_TCP.h"
#include <sys_head.h>

// 初始化函数

int TCP_init(int port)
{
    int server_fd;
    struct sockaddr_in address;
    int opt = 1;

    // 创建套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
    {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 设置套接字选项
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)))
    {
        perror("setsockopt");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 配置地址结构
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(port);

    // 绑定套接字
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0)
    {
        perror("bind failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 监听套接字
    if (listen(server_fd, 3) < 0)
    {
        perror("listen");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    printf("服务器启动成功 端口: %d...\n", port);

    return server_fd;
}

int TCP_accept(int server_fd)
{
    int new_socket;
    struct sockaddr_in client_address;
    socklen_t addrlen = sizeof(client_address);

    // 阻塞等待客户端连接
    if ((new_socket = accept(server_fd, (struct sockaddr *)&client_address, &addrlen)) < 0)
    {
        perror("accept");
        exit(EXIT_FAILURE);
    }

    printf("新连接: socket fd = %d, ip : %s, port: %d\n", new_socket,
           inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port));

    return new_socket;
}


